package com.jh.track.auth.service;



import com.jh.track.admin.api.rpc.UserService;
import com.jh.track.admin.pojo.dto.UserDTO;
import com.jh.track.auth.domain.User;
import com.jh.track.common.core.constant.AuthConstants;
import com.jh.track.common.core.result.Result;
import com.jh.track.common.core.result.ResultCode;
import com.jh.track.common.web.util.RequestUtils;



import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import org.springframework.stereotype.Service;



/**
 * @author ：xy
 * @date ：Created in 2021/4/17 10:49
 * @description：自定义用户认证和授权
 * @version: v 1.0.0
 * @email: xy100826@163.com
*/
@Service
//@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

   // private UserFeignService userFeignService;
    //调用dubbo的RPC
   @DubboReference(version = "${service.version}")
    private UserService userService ;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String clientId = RequestUtils.getAuthClientId();

        User user = null;
        switch (clientId) {
            // 后台用户
            case AuthConstants.ADMIN_CLIENT_ID:
                Result<UserDTO> userRes = userService.getUserByUsername(username);
                if (ResultCode.USER_NOT_EXIST.getCode().equals(userRes.getCode())) {
                    throw new UsernameNotFoundException(ResultCode.USER_NOT_EXIST.getMsg());
                }
               UserDTO userDTO = userRes.getData();
                if (userDTO != null) {
                    userDTO.setClientId(clientId);
                    user = new User(userDTO);
                }
            default:
                break;

        }
        if (!user.isEnabled()) {
            throw new DisabledException("该账户已被禁用!");
        } else if (!user.isAccountNonLocked()) {
            throw new LockedException("该账号已被锁定!");
        } else if (!user.isAccountNonExpired()) {
            throw new AccountExpiredException("该账号已过期!");
        }
        return user;
    }

}
